package com.tang.controller;

import com.tang.enums.AppHttpCodeEnum;
import com.tang.exception.SystemException;
import com.tang.sys.ResponseResult;
import com.tang.sys.entity.User;
import com.tang.sys.service.IBlogLoginService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
public class BlogLoginController {
    @Autowired
    private IBlogLoginService iBlogLoginService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user){
        if (!StringUtils.hasText(user.getUserName())){
            //提示必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        String code = user.getCode();
        // 获取 Redis 中存储的验证码
        String captcha = redisTemplate.opsForValue().get("loginCode:Code");
        // 校验验证码是否正确
        if (!StringUtils.hasText(code) || !code.equalsIgnoreCase(captcha)){
            // 验证码错误，抛出异常
            throw new SystemException(AppHttpCodeEnum.CAPTCHA_ERROR);
        }
        return iBlogLoginService.login(user);
    }

    @PostMapping("/logout")
    public ResponseResult logout(){
        return iBlogLoginService.logout();
    }



}
